/**
 * 
 */
package moneyman;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

/**
 * @author apuranik
 * 
 */
public class Grid extends Canvas {
	private int columns = 0;
	private int rowHeight;
	private String[][] gridValues;
	private int[] gridBackgrounds;

	private int shownRowRangeStart = -1;
	private int shownRowRangeEnd = -1;
	private int showableRows = 0;
	private int[] columnWidth;
	private Graphics g;
	private int screenWidth;
	private int screenHeight;

	public Grid(int rows, int[] columnsPercentage) {
		this.columns = columnsPercentage.length;
		this.columnWidth = new int[this.columns];
		Font font = Font.getDefaultFont();
		rowHeight = font.getHeight();
		screenWidth = getWidth();
		screenHeight = getHeight();
		for (int iCount = 0; iCount < columnsPercentage.length; iCount++) {
			columnWidth[iCount] = (screenWidth * columnsPercentage[iCount]) / 100;
		}

		showableRows = screenHeight / rowHeight;

		gridValues = new String[rows][columns];
		gridBackgrounds = new int[rows];
		gridBackgrounds[0] = Colours.highlightBackGround; // Header background
		gridBackgrounds[rows - 1] = Colours.highlightBackGround; // Foother
		// background
	}

	// public void setRow(String[] values) {
	// int[] colours = new int[this.columns];
	// for (int iCount = 0; iCount < this.columns; iCount++) {
	// colours[iCount] = Colours.normalBackGround;
	// }
	// this. setRow(values, colours);
	// }

	// public void setRow(String[] values, int[] colours) {
	// if (values.length > this.columns) {
	// throw new
	// RuntimeException("Number of values more than number of columns");
	// }
	// }

	public void setRow(int rowNum, String[] values, int colour) {
		if (values.length > this.columns) {
			throw new RuntimeException(
					"Number of values more than number of columns");
		}

		gridValues[rowNum] = values;
		gridBackgrounds[rowNum] = colour;

		this.gridValues[rowNum] = values;
		this.gridBackgrounds[rowNum] = colour;

		if (shownRowRangeStart <= rowNum || rowNum <= shownRowRangeEnd) {
			paintRow(rowNum);
		}
	}

	public void paintRow(int rowNum) {
		int xPoint = 0;
		g.setColor(gridBackgrounds[rowNum]);
		g.fillRect(0, rowNum * rowHeight, screenWidth, rowHeight);
		g.setColor(Colours.normalForeGround);
		for (int iCount = 0; iCount < gridValues[rowNum].length; iCount++) {
			this.g.drawString(gridValues[rowNum][iCount], xPoint, rowNum
					* rowHeight, 0);
			// Move the yPoint forward by a column
			xPoint += columnWidth[iCount];
		}
	}

	protected void paint(Graphics g) {
		this.g = g;
		shownRowRangeStart = 0;
		shownRowRangeEnd = showableRows - 1;
		g.setColor(Colours.normalBackGround);
		g.fillRect(0, 0, screenWidth, screenHeight);
		g.setColor(Colours.normalForeGround);
	}

	protected void scrollUp() {
	}

	protected void scrollDown() {
	}
}
